package com.beiding.controller;

import com.beiding.service.OrderService;
import com.beiding.pojo.order.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@RestController
@RequestMapping("/pay")
public class PayController {


    private OrderService orderService;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    //完成支付的回调
    @PostMapping("/paid")
    void paid(Principal principal, String orderId) {

        orderService.checkHolder(orderId, principal.getName());

        //更改状态位
        orderService.paid(orderId);
    }


    //检查订单是否已经完成付款
    @PostMapping("/hasPaid")
    @Secured("ROLE_TENANT")
    boolean hasPaid(Principal principal, String id) {
        orderService.checkHolder(id, principal.getName());


        //只要不是创建状态都是支付完成
        return orderService.get(id, "state").getState() != Order.CREATE;
    }



    /*
        该接口用于未受理退款以及强制退款

     */

    @PostMapping("/refund")
    @Secured("ROLE_TENANT")
    Order refund(Principal principal, String id, @RequestParam(required = false) String reason) {

        //检查订单持有者
        orderService.checkHolder(id, principal.getName());

        if (reason != null) {
            Assert.isTrue(reason.length() > 2, "退款原因必须多于两个字");
            return orderService.refund(id, reason);

        } else {
            return orderService.refund(id);
        }

    }


    //扣留押金
    @PostMapping("/withholdDeposit")
    @Secured("ROLE_LANDLORD")
    void withholdDeposit(Principal principal, String id, String withholdDepositReason, float depositWithhold) {

        orderService.checkRoomHolder(id, principal.getName());

        Assert.isTrue(withholdDepositReason.length()>2&&withholdDepositReason.length()<16,"至少两个字,最多15个字");

        orderService.withholdDeposit(id, withholdDepositReason, depositWithhold);

    }



}

